package com.GroupSix.service;

import com.GroupSix.dao.QuestionBankDao;
import com.GroupSix.entity.QuestionBankEntity;
import com.GroupSix.vo.QuestionBankEntityVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionBankDao, QuestionBankEntity> implements QuestionBankService {
    //实现增删查改
    //增:添加题目
    @Override
    public Integer add(QuestionBankEntity question){
        question.setQscreateTime(LocalDateTime.now());
        return baseMapper.insert(question);
    }

    // 删：根据ID删除题目
    @Override
    public Integer delete(Long id) {
        return baseMapper.deleteById(id);
    }
    //改:更新题目(需求要输入题目Id才能改)
    @Override
    public Integer update(QuestionBankEntity question) {
        question.setQsupdateTime(LocalDateTime.now());
        return baseMapper.updateById(question);
    }
    //查:根据索引查询
    @Override
    public QuestionBankEntity search(Long id) {
        LambdaQueryWrapper<QuestionBankEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(QuestionBankEntity::getId, id);
        return baseMapper.selectOne(wrapper);
    }
    //查:分页查询
    @Override
    public IPage<QuestionBankEntity> List(QuestionBankEntityVo vo) {
        LambdaQueryWrapper<QuestionBankEntity> wrapper = Wrappers.lambdaQuery();
        // 同时根据学科qsscore和知识点qsknowledge进行筛选，添加相应的条件
        wrapper.eq(ObjectUtils.isNotEmpty(vo.getQscourse()), QuestionBankEntity::getQscourse, vo.getQscourse())
                .eq(ObjectUtils.isNotEmpty(vo.getQsknowledge()), QuestionBankEntity::getQsknowledge, vo.getQsknowledge());
        int curpage = 1;
        int limit = 10;
        if (vo.getCurpage()!= null && vo.getCurpage() > 0) {
            curpage = vo.getCurpage();
        }
        if (vo.getLimit()!= null && vo.getLimit() > 0) {
            limit = vo.getLimit();
        }
        IPage<QuestionBankEntity> page = Page.of(curpage, limit);
        return baseMapper.selectPage(page, wrapper);
    }
    //查重算法
    public boolean existsByContent(String qscontent) {
        QueryWrapper<QuestionBankEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("qscontent", qscontent);
        return baseMapper.selectCount(queryWrapper) > 0;
    }
}